package qrcode;

import java.util.Arrays;
import java.util.Iterator;

public class ByteModeSequence implements QRSequence, Iterable<Boolean> {

  private Version version;

  private byte[] bytes;

  public ByteModeSequence(Version version, byte[] bytes) {
    this.version = version;
    this.bytes = Arrays.copyOf(bytes, bytes.length);
  }

  public ModeIndicator getModeIndicator() {
    return ModeIndicator.BYTE;
  }

  public Version getVersion() {
    return version;
  }

  public int getNumberOfBitsInCharacterCountIndicator() {
    int versionNr = version.getVersionNumber().intValue();
    if (versionNr <= 9)
      return 8;
    return 16;
  }

  @Override
  public Iterator<Boolean> iterator() {
    return new QRSequenceBitIterator(this);
  }

  @Override
  public int getLengthInBits() {
    return 4 + getNumberOfBitsInCharacterCountIndicator() + 8 * bytes.length;
  }

  @Override
  public boolean getSequenceBit(final int idx) {
    if (idx < 4) {
      return BitHelper.getBitAtStartingAtMostSignificant(getModeIndicator().asByte(), 4, idx);
    }
    int tidx = idx - 4;
    if (tidx < getNumberOfBitsInCharacterCountIndicator()) {
      return BitHelper
          .getBitAtStartingAtMostSignificant(bytes.length, getNumberOfBitsInCharacterCountIndicator(), tidx);
    }
    tidx -= getNumberOfBitsInCharacterCountIndicator();
    byte b = bytes[tidx/8];
    return BitHelper.getBitAtStartingAtMostSignificant(b, 8, tidx%8);
  }
  
  public static void main(String[] args) {
    ByteModeSequence seq = new ByteModeSequence(Version.VERSION_1, "Test".getBytes());
    for (Boolean b: seq){
      System.out.print(b.booleanValue()?'1':'0');
    }
  }
}